﻿using System;
using System.IO;
using Yak;

namespace Fancy_Thumb
{
    internal static class Workers
    {

        internal static void SaveIcon(DriveInfo Drive, String IcoFile)
        {
            String Root = Drive.RootDirectory.ToString();
            String AutorunFile = Path.Combine(Root, "Autorun.inf");
            if (IcoFile != null)
                if (IcoFile.StartsWith(Root))
                    NativeMethods.WriteValue(AutorunFile, "AutoRun", "icon", IcoFile.Replace(Root, ""));
                else
                {
                    String NewName = Path.GetFileName(IcoFile);
                    File.Copy(IcoFile, Path.Combine(Root, NewName),true);
                    File.SetAttributes(Path.Combine(Root, NewName), FileAttributes.Hidden);
                    NativeMethods.WriteValue(AutorunFile, "AutoRun", "icon", NewName);
                }
            else
                NativeMethods.WriteValue(AutorunFile, "AutoRun", "icon", "");
            File.SetAttributes(AutorunFile, FileAttributes.Hidden);
        }

        internal static void SaveLabel(DriveInfo Drive, String Label)
        {
            String AutorunFile = Path.Combine(Drive.RootDirectory.ToString(), "Autorun.inf");
            NativeMethods.WriteValue(AutorunFile, "AutoRun", "label", Label);
            File.SetAttributes(AutorunFile, FileAttributes.Hidden);
        }

        internal static String LoadIcon(DriveInfo Drive)
        {
            String AutorunFile = Path.Combine(Drive.RootDirectory.ToString(), "Autorun.inf");
            if (!File.Exists(AutorunFile))
                return null;
            else
            {
                String IcoFile=NativeMethods.ReadValue(AutorunFile, "AutoRun", "icon");
                if (IcoFile != null)
                    return Path.Combine(Drive.RootDirectory.ToString(), IcoFile);
                else
                    return null;
            }
        }

        internal static String LoadLabel(DriveInfo Drive)
        {
            String AutorunFile=Path.Combine(Drive.RootDirectory.ToString(), "Autorun.inf");
            if (!File.Exists(AutorunFile))
            {
                return Drive.VolumeLabel.ToString();
            }
            else
            {
                String Label = NativeMethods.ReadValue(AutorunFile,"AutoRun","label");
                if (Label != null)
                    return Label;
                else
                    return Drive.VolumeLabel.ToString(); 
            }
        }
    }
}
